﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WsGameFrame
{
    public class NewtonJson<T> // where T : new ()
    {
        /// <summary>
        /// 保存的json
        /// </summary>
        public string Json;

        public T JsonStructObj;

        public JObject JsonObj = null;

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="json"></param>
        public NewtonJson(string json)
        {
            Json = json;
        }

        /// <summary>
        /// 获取实体类对象
        /// </summary>
        /// <returns></returns>
        public T GetEntityObject()
        {
            try
            {
                JsonStructObj = JsonConvert.DeserializeObject<T>(Json);
                return JsonStructObj;
            }
            catch(Exception e)
            {
                DebugHelper.Warring(e.Message+"转换Json失败!" + Json);
                return default(T);
            }
        }

        /// <summary>
        /// 获取Json类对象 获取后取值 如:  string name = Theobj["name"].ToString(); 
        /// </summary>
        /// <returns></returns>
        public JObject GetJsonObject()
        {
            try
            {
                JsonObj = JsonConvert.DeserializeObject<JObject>(Json);
                return JsonObj;
            }
            catch
            {
                DebugHelper.Error("转换Json失败!" + Json);
                return null;
            }
        }

        /// <summary>
        /// 转Json
        /// </summary>
        /// <returns></returns>
        public string ToJson()
        {
            try
            {
                if (JsonObj == null)
                {
                    Json = JsonConvert.SerializeObject(JsonStructObj);
                }
                else
                {
                    Json = JsonConvert.SerializeObject(JsonObj);
                }
                return Json;
            }
            catch
            {
                DebugHelper.Error("转换Json失败!" + Json);
                return null;
            }
        }

        /// <summary>
        /// 转json
        /// </summary>
        /// <param name="JsonObj"></param>
        /// <returns></returns>
        public static string ToJson(T JsonObj)
        {
            try
            {
                return JsonConvert.SerializeObject(JsonObj);
            }
            catch
            {
                DebugHelper.Error("转换Json失败!" + typeof(T));
                return null;
            }
        }
    }
}
